<template>
    <div>
        <el-form :inline="true" label-width="100px" class="toolbar">
            <template v-for="(condition, cIndex) in query.SearchConditions" :key="cIndex">
                <el-form-item :label="condition.Label">
                    <template v-for="(conditionModel, mIndex) in condition.ConditionalModels" :key="mIndex">
                        <el-date-picker
                            v-if="isDateField(condition, conditionModel)"
                            v-model="conditionModel.FieldValue"
                            type="date"
                            placeholder="请选择日期"
                            value-format="YYYY-MM-DD"
                            style="width: 240px" />
                        <el-input
                            v-else
                            v-model="conditionModel.FieldValue"
                            clearable
                            placeholder="请输入"
                            style="width: 240px"
                            @keyup.enter="getDataList"
                            @input="debouncedSearch" />
                    </template>
                </el-form-item>
            </template>
            <el-form-item>
                <el-button type="primary" @click="getDataList">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
                <el-button type="primary" @click="handleEdit()">新增</el-button>
            </el-form-item>
        </el-form>
    </div>
    <el-table v-loading="isLoading" height="600px" :show-overflow-tooltip="true" :data="tableData">
        <el-table-column v-for="item in safeColumns" :key="item.Name" :prop="item.Name" :label="item.Label">
            <template #default="scope">
                <template v-if="item.TypeName == 'DateTime' || item.ControlType == 5">{{
                    moment(scope.row[item.Name]).format('YYYY-MM-DD HH:mm:ss') }}</template>
                <template v-else>
                    {{ maskIfSensitive(item.Name, scope.row[item.Name]) }}
                </template>
                <!-- {{ scope.row[item.Name] }} -->
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
            <template #default="scope">
                <el-button link type="primary" @click="handleEdit(scope.row)" size="small">编辑</el-button>
                <el-button link type="primary" @click="onCopy(scope.row)" size="small">复制</el-button>
                <el-popconfirm title="确定删除?" @confirm="handleDelete(scope.row)">
                    <template #reference>
                        <el-button link type="danger" size="small">删除</el-button>
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>
    <div style="display:flex; justify-content:flex-end; padding: 12px 0;">
        <el-pagination
            v-model:current-page="query.pageIndex"
            v-model:page-size="query.pageSize"
            :total="total"
            :page-sizes="[10,20,30,50]"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="getDataList"
            @size-change="onPageSizeChange" />
    </div>

    <EditDialog ref="dialogRef" @confirm="onConfirm" :bgcolumnNames="currentEditColumns"></EditDialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus'
import moment from 'moment';

import EditDialog from '../components/EditDialog.vue';
import api from '../api'
const query = reactive({
    pageIndex: 1,
    pageSize: 30,
    SearchConditions:[{"Label":"UserName","ConditionalModels":[{"FieldName":"UserName","FieldValue":null,"CSharpTypeName":"String","CustomConditionalFunc":null,"CustomParameterValue":null,"ConditionalType":1}],"ControlType":3},{"Label":"PasswordHash","ConditionalModels":[{"FieldName":"PasswordHash","FieldValue":null,"CSharpTypeName":"String","CustomConditionalFunc":null,"CustomParameterValue":null,"ConditionalType":1}],"ControlType":3},{"Label":"Salt","ConditionalModels":[{"FieldName":"Salt","FieldValue":null,"CSharpTypeName":"String","CustomConditionalFunc":null,"CustomParameterValue":null,"ConditionalType":1}],"ControlType":3},{"Label":"上次登录时间","ConditionalModels":[{"FieldName":"LastLoginDate","FieldValue":null,"CSharpTypeName":"Nullable`1","CustomConditionalFunc":null,"CustomParameterValue":null,"ConditionalType":0}],"ControlType":3}]
})
var isLoading = ref(false)
var tableData = ref([])
var total = ref(0)
const dialogRef = ref<InstanceType<typeof EditDialog>>();
var bgcolumnNames=[{"Name":"UserName","Order":100,"Label":"UserName","ControlType":3,"TypeName":"String","IsShow":true,"IsEditable":true,"IsNullable":true,"EnumDic":null},{"Name":"PasswordHash","Order":100,"Label":"PasswordHash","ControlType":3,"TypeName":"String","IsShow":true,"IsEditable":true,"IsNullable":true,"EnumDic":null},{"Name":"Salt","Order":100,"Label":"Salt","ControlType":3,"TypeName":"String","IsShow":true,"IsEditable":true,"IsNullable":true,"EnumDic":null},{"Name":"LastLoginDate","Order":100,"Label":"上次登录时间","ControlType":3,"TypeName":"Nullable`1","IsShow":true,"IsEditable":true,"IsNullable":true,"EnumDic":null}]


onMounted(async () => {
    try {
        getDataList()
        // const data = await $api.get('/your-api-endpoint');
        // 使用获取的数据
    } catch (error) {

    }
});

// 判断是否为日期字段（用于渲染日期选择器）
const isDateField = (condition, model) => {
    if (!condition || !model) return false
    return (condition.Label && condition.Label.indexOf('时间') >= 0) ||
           (model.FieldName && model.FieldName.toLowerCase().includes('date'))
}

// 简易去抖
function debounce(fn: Function, delay = 300) {
    let timer: any = null
    return (...args: any[]) => {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => fn.apply(null, args), delay)
    }
}
const debouncedSearch = debounce(() => getDataList(), 300)

const resetQuery = () => {
    console.log('reset', query.SearchConditions)
    query.SearchConditions.forEach(item => {
        item.ConditionalModels.forEach(modelItem => {
            modelItem.FieldValue = null
        })
    })
    getDataList()
}
const onCopy = async item => {
    var copyItem = JSON.parse(JSON.stringify(item));
    copyItem.Id = 0
    dialogRef.value.open(copyItem)
}
const handleEdit = async (item?: any) => {
    console.log('handleEdit',item)  ;
    // 若未传入 item，则视为新增，打开空白表单
    if (!item) {
        const blank: any = { Id: 0 }
        baseFormColumns.forEach(col => {
            blank[col.Name] = null
        })
        blank['Password'] = ''
        currentEditColumns.value = [...baseFormColumns, passwordColumn]
        console.log('currentEditColumns 新增',currentEditColumns.value)  ;
        dialogRef.value.open(blank)
        return
    }
    var editItem = JSON.parse(JSON.stringify(item));
    currentEditColumns.value = [...baseFormColumns]
    console.log('currentEditColumns 编辑',currentEditColumns.value)  ;
    dialogRef.value.open(editItem)
}
// 定义方法
const getDataList = async () => {
    isLoading.value = true
    var res = await api.post('User/List', query)
    isLoading.value = false
    var data = res.Data
    tableData.value = data.list
    total.value = data.total ?? 0
    // bgcolumnNames = data.columnNames

};

console.log('baseFormColumns',bgcolumnNames)  ;
// 安全列（隐藏敏感列&上次登录时间不在表格显示）
const safeColumns = bgcolumnNames.filter(x => x.Name !== 'PasswordHash' && x.Name !== 'Salt' && x.Name !== 'LastLoginDate')
// 表单基础列：不包含上次登录时间
const baseFormColumns = safeColumns.filter(x => x.Name !== 'LastLoginDate')
// 编辑弹窗使用的列（同样隐藏敏感字段）；新增时注入虚拟 Password 字段
const passwordColumn = { Name: 'Password', Label: 'Password', ControlType: 3, TypeName: 'String', IsShow: true, IsEditable: true, IsNullable: false }
const currentEditColumns = ref<any[]>(baseFormColumns)

const maskIfSensitive = (name: string, value: any) => {
    if (name === 'PasswordHash' || name === 'Salt') {
        if (!value) return ''
        const str = String(value)
        return str.length <= 6 ? '******' : str.slice(0, 3) + '***' + str.slice(-3)
    }
    return value
}

const onPageSizeChange = (size: number) => {
    query.pageSize = size
    query.pageIndex = 1
    getDataList()
}

/**
 * 确认并更新模板信息
 * 无参数
 * 无明确返回值，但会通过控制台输出和界面提示更新结果
 */
const onConfirm = async (item) => {
    // 根据是否为新增调用不同接口
    let res
    if (!item.Id || Number(item.Id) === 0) {
        // 新增：使用注册接口，并从表单获取明文 Password
        const payload = { UserName: item.UserName, Password: item.Password }
        res = await api.post('User/Register', payload)
    } else {
        // 编辑：不处理密码
        res = await api.post('User/Update', item)
    }

    // 根据服务器返回代码判断操作成功与否
    if (res.Code == 200) {
        //隐藏对话框
        dialogRef.value.close()
        // 成功更新，显示成功消息并刷新列表
        ElMessage({
            message: res.Message,
            type: 'success',
        })
        getDataList()
    }
}
const handleDelete = async item => {

    item.isDeleted = true
    var res = await api.post('User/Update', item)
    if (res.Code == 200) {
        // 成功更新，显示成功消息并刷新列表
        ElMessage({
            message: "删除成功",
            type: 'success',
        })
        getDataList()
    }
}


</script>

<style>
.CodeMirror {
    margin-right: 100px;
}

.CodeMirror-sizer {
    min-width: 500px !important;
}

.el-dialog__body {
    overflow: auto;
    max-height: 500px;
}
</style>